// [参考](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-point/)

export default class EditControl {
	constructor(map) {
		this.map = map;
		this.canvas = map.getCanvasContainer();

		this.points = [];
		this.editSource = null;

		this.enterFunc = null;
		this.leaveFunc = null;
		this.downFunc = null;
		this.moveFunc = null;
		this.upFunc = null;
	}

	bindEvents(callback) {
		const { map, editLayerId } = this;

		this.enterFunc = this.onMouseEnter.bind(this);
		this.leaveFunc = this.onMouseLeave.bind(this);
		this.downFunc = this.onMouseDown.bind(this);
		this.moveFunc = this.onMove.bind(this, callback);
		this.upFunc = this.onUp.bind(this);

		map.on("mouseenter", editLayerId, this.enterFunc);
		map.on("mouseleave", editLayerId, this.leaveFunc);
		map.on("mousedown", editLayerId, this.downFunc);
	}

	onMouseEnter() {
		const { canvas } = this;
		canvas.style.cursor = "move";
	}

	onMouseLeave() {
		const { canvas } = this;
		canvas.style.cursor = "";
	}

	onMouseDown(e) {
		// Prevent the default map drag behavior.
		e.preventDefault();

		const { canvas, map } = this;

		canvas.style.cursor = "grab";

		map.on("mousemove", this.moveFunc);
		map.once("mouseup", this.upFunc);
	}

	onUp() {
		const { canvas, map } = this;

		canvas.style.cursor = "";

		map.off("mousemove", this.moveFunc);
	}

	destroy() {
		const { map, editLayerId } = this;

		map.off("mouseenter", this.enterFunc);
		map.off("mouseleave", this.leaveFunc);
		map.off("mousedown", this.downFunc);

		map.removeLayer(editLayerId);
		map.removeSource(editLayerId);
	}
}
